package com.ray.common.util;

import java.text.SimpleDateFormat;
import java.util.Date;

import com.zjhc.flyhong.redis.DefaultRedisService;
import com.zjhc.flyhong.redis.RedisDistributedCounterObject;

/**
 * redis序号
 * @author ray
 *
 */
public class RedisNoUtil {
    
    public static String createNo(String prefix,int zise ,DefaultRedisService defaultRedisService) {
        String key = prefix+new SimpleDateFormat("yyyyMMdd").format(new Date());
        return getSeqEveryDayAll(prefix,key, zise,defaultRedisService);
    }
    
    public static String createNo(String prefix ,DefaultRedisService defaultRedisService) {
       return createNo(prefix,8,defaultRedisService);
    }
    
    /**
     * @Description: 根据code那么获取sequence 拼接codename
     * @param  codeName
     * @param  leng 左边补0几位
     * @return String 返回类型
     * @throws 异常说明
     * 
     * @author zhaohp
     */
    private static String getSeqEveryDayAll(String prefix,String key, int leng,DefaultRedisService defaultRedisService){
        // 0 代表前面补充0      
        // leng 代表长度为leng     
        // d 代表参数为正数型       
        return key+String.format("%0"+leng+"d", getSeqEveryDay(key,defaultRedisService));
    }
    
    /**
     * @Description: 根据code那么获取sequence
     * @param  codeName
     * @return String 返回类型
     * @throws 异常说明
     * 
     * @author zhaohp
     */
    private static Long getSeqEveryDay(String codeName ,DefaultRedisService defaultRedisService) {
    	//defaultRedisService.setKeyNamespace(new RedisKeyNamespace("flyhong:dcounter"));
        String now = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = "";
        if (!codeName.startsWith("sequence:")) {
            key = "sequence:" + codeName;
        } else {
            key = codeName;
        }
        if (!codeName.endsWith(now))
            key += now;
       
        RedisDistributedCounterObject counterObject = new RedisDistributedCounterObject(key); 
        defaultRedisService.doExpire(key, 24*60*60*1000);
        return defaultRedisService.increase(counterObject, 1);
    }
    
   
}
